package com.example.qixinshangwutong;

import android.app.Application;
import android.util.Log;

import com.example.qixinshangwutong.presenter.API;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import cn.leancloud.LCLogger;
import cn.leancloud.LeanCloud;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


public class BaseApplication extends Application {
    public static API api;
    private static final String TAG="tag";
    @Override
    public void onCreate() {
        super.onCreate();
//在LeanCloud.initialize()之前调用
        LeanCloud.setLogLevel(LCLogger.Level.DEBUG);
        LeanCloud.initialize("HCJDor8HfA1q0YfKq0XkLTrx-gzGzoHsz",
                "g2vhCTq3iYpn2y0pQJz9yLVi","https://hcjdor8h.lc-cn-n1-shared.com");

        Retrofit retrofit=new Retrofit.Builder().baseUrl("http://api.qxswt.com")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(new OkHttpClient.Builder()
                .callTimeout(5, TimeUnit.SECONDS)
                        .connectTimeout(10,TimeUnit.SECONDS)
                        .readTimeout(5,TimeUnit.SECONDS)
                        .addInterceptor(new Interceptor() {
                            @NotNull
                            @Override
                            public Response intercept(@NotNull Chain chain) throws IOException {
                                Request request = chain.request();
                                String url = request.url().url().toString();

                                if (null != request.body()) {
                                    String type = request.body().contentType().type();
                                    String param = request.body().toString();
                                    Log.d(TAG, "请求参数=" + param);
                                    Log.d(TAG, "参数类型=" + type);
                                }
                                Response response = chain.proceed(request);
                                String result = response.body().string();
                                Log.d(TAG, "请求地址=" + url);
                                Log.d(TAG, "response=" + result);
                                return response.newBuilder()
                                        .body(ResponseBody.create(response.body().contentType(), result)).build();
                            }
                        }).build()).build();
        createRequest(retrofit);

    }
    private void createRequest(Retrofit retrofit){
       api =retrofit.create(API.class);
    }
}
